package com.ruoyi.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.contract.domain.ConBusiness;
import com.ruoyi.contract.domain.ConCusRela;
import com.ruoyi.contract.domain.VCtmsClient;
import com.ruoyi.contract.domain.vo.ConBusinessDetail;
import com.ruoyi.contract.mapper.ConCusRelaMapper;
import com.ruoyi.contract.service.IConCusRelaService;
import com.ruoyi.contract.service.VCtmsClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangxiang on 2021/9/17.
 */
@Service
public class ConCusRelaServiceImpl extends ServiceImpl<ConCusRelaMapper, ConCusRela> implements IConCusRelaService {

    @Autowired
    ConCusRelaMapper conCusRelaMapper;

    @Autowired
    VCtmsClientService vCtmsClientService;





    @Override
    public boolean addConCusRelaByConBusiness(ConBusiness conBusiness, ConBusinessDetail conBusinessDetail) {
        List<ConCusRela> conCusRelaList = new ArrayList<>();
        for(String partA : conBusinessDetail.getCustomerGkeys()){
            VCtmsClient vCtmsClient = vCtmsClientService.getOne(
                    new QueryWrapper<VCtmsClient>().lambda().eq(VCtmsClient::getCustomerGkey,partA));
            ConCusRela conCusRela = new ConCusRela();
            conCusRela.setConId(conBusiness.getConId());
            conCusRela.setCustomerGkey(vCtmsClient.getCustomerGkey());
            conCusRelaList.add(conCusRela);
        }
        return this.saveBatch(conCusRelaList);
    }

    @Override
    public String getRelationNamesByConId(Long conId, String part) {
        List<ConCusRela> conCusRelaList = this.list(new QueryWrapper<ConCusRela>().lambda().eq(ConCusRela::getConId,conId));
        StringBuffer names = new StringBuffer();
        for(ConCusRela conCusRela : conCusRelaList){
            VCtmsClient vCtmsClient = vCtmsClientService.getOne(
                    new QueryWrapper<VCtmsClient>().lambda().eq(VCtmsClient::getCustomerGkey,conCusRela.getCustomerGkey()));
            names.append(vCtmsClient.getCnCustomerNam()).append("，");
        }
        if(names.length()>0){
            names.deleteCharAt(names.length()-1);
        }
        return names.toString();
    }

    @Override
    public boolean cloneConCusRela(Long oldConId, Long newConId) {
        List<ConCusRela> conCusRelaList = this.list(new QueryWrapper<ConCusRela>().lambda().eq(ConCusRela::getConId,oldConId));
        for(int i=0;i<conCusRelaList.size();i++){
            conCusRelaList.get(i).setConId(newConId);
            conCusRelaList.get(i).setContrastId(null);
        }
        return this.saveBatch(conCusRelaList);
    }
}
